const {app, BrowserWindow} = require('electron')
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog

const key_host = "host"
const key_access_token = "accesstoken"
const key_feed_token = "feedtoken"

let mainWindow
let db
let gitlab_host = null, gitlab_access_token = null, gitlab_feed_token = null

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg= new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

// https://blog.csdn.net/chenzhigaoa/article/details/80284629
ipc.on('gitlab_config', function(event, arg) {
    var first_insert = false
    var sub_msg = "successful"
    if(gitlab_host === null && gitlab_access_token === null 
        && gitlab_feed_token === null) {
        first_insert = true
    }
    // get gitlab config
    gitlab_host = arg[0]
    gitlab_access_token = arg[1]
    gitlab_feed_token = arg[2]

    // update data to db
    if(db !== null) {
        db.serialize(function() {
            if(first_insert) {
                var stmt = db.prepare("INSERT INTO config (category, key, val) VALUES (?, ?, ?)")
                stmt.run(["gitlab", key_host, gitlab_host])
                stmt.run(["gitlab", key_access_token, gitlab_access_token])
                stmt.run(["gitlab", key_feed_token, gitlab_feed_token])
                stmt.finalize()
                sub_msg = "First init successful."
            } else {
                // try to query value first
                keys = [ key_host, key_access_token, key_feed_token ]
                vals = {
                    "host": gitlab_host,
                    "accesstoken": gitlab_access_token,
                    "feedtoken": gitlab_feed_token
                }

                let check_config = function(key) {
                    db.get("SELECT val FROM config WHERE category = ? AND key = ?",
                                             [ "gitlab", key ], function(err, res) {
                        if(typeof(res) == "undefined") {
                            // insert the value
                            db.run("INSERT INTO config (category, key, val) VALUES (?, ?, ?)",
                                     [ "gitlab", key, vals[key] ], function(er, sres) {
                                         console.log("Insert operation: ", er, sres)
                                     })
                        } else {
                            // update the value
                            console.log(vals[key])
                            console.log("Update k {0} v {1}.".format(key, vals[key]))
                            db.run("UPDATE config SET val = ? WHERE category = 'gitlab' AND key = ?",
                                     [ vals[key], key ], function(er, sres) {
                                         console.log("Update operation: ", er, sres)
                                     })
                        }
                    })
                }
                for(inx in keys) {
                    var key = keys[inx]
                    console.log("Check config {0} ...".format(key))
                    check_config(key)
                }
                sub_msg = "Update successful."
            }
        })
        // draw a message box
        const options = {
            type: 'info',
            title: 'Information',
            message: "GitLab config completed: {0}.".format(sub_msg),
            buttons: [ "Ok" ]
        }
        dialog.showMessageBox(options, function(index) {
            console.log("index: ", index)
        })
    }
})

ipc.on('gitlab_test', function(event, arg) {
    var operation = arg
    var msg = "Unknown test operation."
    if(operation == "connect_test") {
        msg = "Test Gitlab connection."
        if(gitlab_host === null) {
            msg = "Missing Gitlab host, please config it first!"
        } else if(gitlab_access_token === null) {
            msg = "Missing Gitlab access token, please config it first!"
        } else if(gitlab_feed_token === null) {
            msg = "Missing Gitlab feed token, please config it first!"
        } else {
            // test gitlab connection
            console.log("Begin to test gitlab connection...")
            msg += "Git Lab host {0}, access token {1}, feed token {2}.".format(gitlab_host,
                                                     gitlab_access_token, gitlab_feed_token)
        }
    }
    const options = {
        type: 'info',
        title: "Information",
        message: msg,
        buttons: [ "Ok" ]
    }
    dialog.showMessageBox(options, function(index) {
        console.log("index: ", index)
    })
})

// function createSubWindow() {
//     const BrowserWindow = require('electron').remote.BrowserWindow
//     const path = require('path')

//     const newWindowBtn = document.getElementById('new-window')
//     newWindowBtn.addEventListener('click', function(event){
//         const modalPath = path.join('file://', __dirname, '../../sections/windows/')
//         let win = new BrowserWindow({ width: 400, height: 320 })
//         win.on('close', function(){ win = null })
//         win.loadURL(modalPath)
//         win.show()
//     })
// }

function createWindow() {
    mainWindow = new BrowserWindow({width: 800, height: 600})

    // init db
    var sqlite3 = require('sqlite3').verbose()
    const path = require('path')
    db = new sqlite3.Database(path.join(__dirname, 'config.db'))
    db.serialize(function(){
        db.run("CREATE TABLE IF NOT EXISTS config (id INTEGER PRIMARY KEY AUTOINCREMENT, category VARCHAR(255), key VARCHAR(255), val VARCHAR(255))")
        // try to query record from config table
        // gitlab config
        db.each("SELECT key, val FROM config WHERE category=?", [ "gitlab" ], function(err, res) {
            if(typeof(res) == "undefined") {
                console.log("There is no related config of gitlab now.")
            } else {
                if(res["key"] == key_host) {
                    gitlab_host = res["val"]
                } else if(res["key"] == key_access_token) {
                    gitlab_access_token = res["val"]
                } else if(res["key"] == key_feed_token) {
                    gitlab_feed_token = res["val"]
                }
            }
        })
    })

    mainWindow.loadFile('index.html')

    mainWindow.on('closed', function() {
        mainWindow = null
        if(db !== null) {
            // close db if app closed
            db.close()
        }
    })
}

// app start
app.on('ready', createWindow)

// app quit
app.on('window-all-closed', function() {
    if(process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function() {
    if(mainWindow === null) {
        createWindow()
    }
})
